package com.earl.handler;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.hibernate.validator.constraints.pl.REGON;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 知鹏 on 2018/6/24.
 */
@Controller
public class TestCode {


    @RequestMapping("/test")
    public void Test() {
        System.out.println("中文");
    }

    //通过get方法发送请求

    public static void downloadPage(String path, String callback) throws HttpException, IOException {//headerLength是上述图片中的callback
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(path);//path就是上述的Request URL
        httpGet.setHeader("Connection", "keep-alive");
        httpGet.setHeader("User-A", "Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2");
        int headerLength=callback.length();

        CloseableHttpResponse response = httpclient.execute(httpGet);

        int statusCode = response.getStatusLine().getStatusCode();
        HttpEntity entity = response.getEntity();

        if (statusCode == HttpStatus.SC_OK) {
            InputStream input = null;
//将请求后反应得到的数据写入输入流
            input = entity.getContent();

            BufferedReader br = new BufferedReader(new InputStreamReader(input));

            String line = null;
            while ((line = br.readLine()) != null) {
//把得到的不规范的json数据裁剪
                String reqBody = line.toString().substring(headerLength + 1, line.length() - 2);

                JsonParser parser = new JsonParser();
                try {
// 将json格式的字符串转换成json对象
                    JsonObject json = parser.parse(reqBody).getAsJsonObject();

// 得到键是comments的json数组,此时的json数组是键值对的数组
                    JsonArray jsonArray = json.getAsJsonArray("comments");

                    String num= String.valueOf(json.getAsJsonPrimitive("maxPage"));

                    System.out.println(num+"numnumnumnumnumnumnumnumnumnum");

                    int length = jsonArray.size();
                    for (int i = 0; i < length; i++) {
// 得到一条评论信息
                        JsonElement element = jsonArray.get(i);

// 裁剪没用的json格式，得到评论信息
                        String midContent = element.getAsJsonObject().get("content").toString();

//去除文本首尾的引号
                        String content = midContent.substring(1, midContent.length() - 1);
// 保留原文件的，在原文件的末尾继续写入输出文件

                            System.out.println(content);
                        }

                    }catch (Exception e){
                    System.out.println(e);
                }


                }
            }
        }

    /**
     * 解析出url参数中的键值对
     * 如 "index.jsp?Action=del&id=123"，解析出Action:del,id:123存入map中
     * @param URL  url地址
     * @return  url请求参数部分
     */
    public static Map<String, String> URLRequest(String URL)
    {
        Map<String, String> mapRequest = new HashMap<String, String>();

        String[] arrSplit=null;

        String strUrlParam=truncateUrlPage(URL);
        if(strUrlParam==null)
        {
            return mapRequest;
        }
        //每个键值为一组 www.2cto.com
        arrSplit=strUrlParam.split("[&]");
        for(String strSplit:arrSplit)
        {
            String[] arrSplitEqual=null;
            arrSplitEqual= strSplit.split("[=]");

            //解析出键值
            if(arrSplitEqual.length>1)
            {
                //正确解析
                mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);

            }
            else
            {
                if(arrSplitEqual[0]!="")
                {
                    //只有参数没有值，不加入
                    mapRequest.put(arrSplitEqual[0], "");
                }
            }
        }
        return mapRequest;
    }
    /**
     * 去掉url中的路径，留下请求参数部分
     * @param strURL url地址
     * @return url请求参数部分
     */
    private static String truncateUrlPage(String strURL)
    {
        String strAllParam=null;
        String[] arrSplit=null;

        strURL=strURL.trim().toLowerCase();

        arrSplit=strURL.split("[?]");
        if(strURL.length()>1)
        {
            if(arrSplit.length>1)
            {
                if(arrSplit[1]!=null)
                {
                    strAllParam=arrSplit[1];
                }
            }
        }

        return strAllParam;
    }
}






